import 'package:flutter/material.dart';
import '../theme/app_theme.dart';

/// 笔记数据模型
class NoteItem {
  final String id;
  final String title;
  final String content;
  final DateTime createdAt;
  final DateTime updatedAt;
  final bool isSelected;

  const NoteItem({
    required this.id,
    required this.title,
    required this.content,
    required this.createdAt,
    required this.updatedAt,
    this.isSelected = false,
  });

  /// 创建副本并更新指定字段
  NoteItem copyWith({
    String? id,
    String? title,
    String? content,
    DateTime? createdAt,
    DateTime? updatedAt,
    bool? isSelected,
  }) {
    return NoteItem(
      id: id ?? this.id,
      title: title ?? this.title,
      content: content ?? this.content,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      isSelected: isSelected ?? this.isSelected,
    );
  }

  /// 获取内容预览（去除 Markdown 格式）
  String get preview {
    String cleanContent = content
        .replaceAll(RegExp(r'#{1,6}\s+'), '') // 移除标题标记
        .replaceAll(RegExp(r'\*\*(.*?)\*\*'), r'$1') // 移除粗体标记
        .replaceAll(RegExp(r'\*(.*?)\*'), r'$1') // 移除斜体标记
        .replaceAll(RegExp(r'`(.*?)`'), r'$1') // 移除代码标记
        .replaceAll(RegExp(r'\[(.*?)\]\(.*?\)'), r'$1') // 移除链接标记
        .replaceAll(RegExp(r'^\s*[-*+]\s+', multiLine: true), '') // 移除列表标记
        .replaceAll(RegExp(r'\n+'), ' ') // 替换换行为空格
        .trim();
    
    return cleanContent.length > 100 
        ? '${cleanContent.substring(0, 100)}...' 
        : cleanContent;
  }

  /// 格式化时间显示
  String get formattedTime {
    final now = DateTime.now();
    final difference = now.difference(updatedAt);
    
    if (difference.inDays > 0) {
      return '${updatedAt.month}月${updatedAt.day}日 ${updatedAt.hour.toString().padLeft(2, '0')}:${updatedAt.minute.toString().padLeft(2, '0')}';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
}

/// 笔记列表组件
/// 显示笔记标题、预览内容和更新时间
class NoteList extends StatefulWidget {
  final List<NoteItem> notes;
  final String? selectedNoteId;
  final Function(String noteId)? onNoteSelected;
  final VoidCallback? onNewNote;

  const NoteList({
    super.key,
    required this.notes,
    this.selectedNoteId,
    this.onNoteSelected,
    this.onNewNote,
  });

  @override
  State<NoteList> createState() => _NoteListState();
}

class _NoteListState extends State<NoteList> {
  /// 构建笔记列表项
  Widget _buildNoteItem(NoteItem note) {
    final isSelected = note.id == widget.selectedNoteId;
    
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => widget.onNoteSelected?.call(note.id),
          borderRadius: BorderRadius.circular(8),
          child: Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: isSelected ? AppTheme.sidebarSelected : Colors.transparent,
              borderRadius: BorderRadius.circular(8),
              border: isSelected 
                  ? Border.all(color: AppTheme.primaryColor.withOpacity(0.3), width: 1)
                  : null,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 笔记标题
                Text(
                  note.title.isEmpty ? '无标题' : note.title,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: isSelected ? AppTheme.primaryColor : AppTheme.textPrimary,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                
                const SizedBox(height: 6),
                
                // 笔记预览
                if (note.preview.isNotEmpty)
                  Text(
                    note.preview,
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppTheme.textSecondary,
                      height: 1.3,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                
                const SizedBox(height: 8),
                
                // 更新时间
                Text(
                  note.formattedTime,
                  style: const TextStyle(
                    fontSize: 11,
                    color: AppTheme.textTertiary,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.note_add_outlined,
            size: 64,
            color: AppTheme.textTertiary,
          ),
          const SizedBox(height: 16),
          const Text(
            '还没有笔记',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: AppTheme.textSecondary,
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            '点击新建按钮开始写作',
            style: TextStyle(
              fontSize: 14,
              color: AppTheme.textTertiary,
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: widget.onNewNote,
            icon: const Icon(Icons.add, size: 18),
            label: const Text('新建笔记'),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.primaryColor,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              elevation: 0,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建列表头部
  Widget _buildListHeader() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
      child: Row(
        children: [
          const Text(
            '测试文件夹',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: AppTheme.textPrimary,
            ),
          ),
          const Spacer(),
          Text(
            '${widget.notes.length} 个笔记',
            style: const TextStyle(
              fontSize: 12,
              color: AppTheme.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 320,
      decoration: const BoxDecoration(
        color: AppTheme.surfaceLight,
        border: Border(
          right: BorderSide(
            color: AppTheme.borderColor,
            width: 0.5,
          ),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 列表头部
          _buildListHeader(),
          
          // 分割线
          const Divider(
            height: 1,
            color: AppTheme.borderColor,
            indent: 16,
            endIndent: 16,
          ),
          
          // 笔记列表
          Expanded(
            child: widget.notes.isEmpty
                ? _buildEmptyState()
                : ListView.builder(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    itemCount: widget.notes.length,
                    itemBuilder: (context, index) {
                      return _buildNoteItem(widget.notes[index]);
                    },
                  ),
          ),
        ],
      ),
    );
  }
}